﻿using System;
using System.Windows.Input;
using ClientOverflow.Core;
using ClientOverflow.DataTransferObjects;
using ClientOverflow.ViewModels.Interfaces;

namespace ClientOverflow.ViewModels.QuestionViewViewModels
{
    /// <summary>
    /// PostNewAnswerCommand is a command in charge of sending a new answer to the DB through the
    /// WCF service. The command creates a DTO from the new answer view-model and pass it through
    /// the service to the server side.
    /// </summary>
    internal class PostNewAnswerCommand : ICommand
    {
        private readonly Question question;
        private readonly INewAnswerViewModel newAnswer;

        public event Action Executed = () => { };

        public PostNewAnswerCommand(Question question, INewAnswerViewModel newAnswer)
        {
            this.question = question;
            this.newAnswer = newAnswer;
            this.newAnswer.PropertyChanged += (sender, args) => CanExecuteChanged(this, EventArgs.Empty);
        }

        public void Execute(object parameter)
        {
            using (var serviceClient = ServicesFactory.CreateClientOverflowServiceClient())
            {
                var loggenInUser = ServicesProviderFactory.GetInstance().LoginService.LoggenInUser;
                serviceClient.PostAnswer(question, new Answer {Content = newAnswer.Content}, loggenInUser);
            }

            Executed();
        }

        public bool CanExecute(object parameter)
        {
            return !string.IsNullOrWhiteSpace(newAnswer.Content);
        }

        public event EventHandler CanExecuteChanged = (sender, args) => { };
    }
}